//
//  ChangeMTViewController.m
//  carcareIOS
//
//  Created by wr on 15/8/31.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "ChangeMTViewController.h"
#import "changeMTCell.h"
#import "OrderSureViewController.h"
#import "RefreshMgr.h"

#define SECTION_HEIGHT (46)
#define SECTION_HEIGHT_SMALL (9.5)
#define CELL_HEIGHT_NORMALL (55)
#define CELL_HEIGHT_CONTENT (48)
#define FOOT_BOTTOM_HEIGHT (55)

@interface ChangeMTViewController ()<UITableViewDataSource , UITableViewDelegate>

@property (nonatomic , readonly) NSArray * sectionTitleArray;

@property (nonatomic , strong) UITableView * tableView;

@property (nonatomic , copy) NSArray * dataArray;

// 提交
@property (nonatomic , strong) UIButton * submitButton;

//金额合计
@property (nonatomic , strong) UILabel * moneyCountLabel;

@property (nonatomic , readonly) NSDictionary * iconImageDic;

//挣点
@property (nonatomic , assign) BOOL isSwitchOn;

@property (nonatomic , assign) NSInteger earnMoneyInt;

@property (nonatomic , assign) CGFloat totalPriceFloat;

@property (nonatomic, strong) RefreshMgr *refreshMgr;

@end

@implementation ChangeMTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"保养服务项目";
    
    self.isSwitchOn = YES;
    
    self.dataArray = [MaintenanceMgr sharedInstance].choiceServiceList.model.categoryModels;
    
    [self createTableView];
    
    [self createFootView];
    
    [self loadData];
}
- (void)loadData
{
    self.refreshMgr = [RefreshMgr sharedInstance];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMoney) name:REFRESH_MONEY object:nil];
    
    self.earnMoneyInt = [self loadEarnMoneyInt:self.refreshMgr.refreshMoney.currentMoney withPrice:self.totalPriceFloat];
    
    [_tableView reloadData];
    [self loadFootViewData];
}
-(void)updateMoney{
    
    self.earnMoneyInt = [self loadEarnMoneyInt:self.refreshMgr.refreshMoney.currentMoney withPrice:self.totalPriceFloat];
    
    [_tableView reloadData];
    [self loadFootViewData];
}
#pragma mark - 根据当前剩余挣点数  和 订单总价格   获取 可以兑换的挣点数
- (NSInteger)loadEarnMoneyInt:(NSInteger)earnMoneyInt withPrice:(double)priceDouble
{
    NSInteger newEarnMoneyInt = 0;
    if(earnMoneyInt > (NSInteger)(priceDouble * 10))
    {
        newEarnMoneyInt = (NSInteger)(priceDouble * 10);
    }else
    {
        newEarnMoneyInt = earnMoneyInt;
    }
    return newEarnMoneyInt;
}
- (NSDictionary *)iconImageDic
{
    return @{@"机油":@"oilMTIconImage",@"机油滤清器":@"oilCleanerIconImage",@"空气滤清器":@"airClearnerIconImage",@"博湃专属PM2.5滤芯":@"boPaiIconImage"};
}
- (void)createFootView
{
    UIView * footBottomView = [Factory viewWithFrame:CGRectMake(0, __MAIN_HEIGHT_64  - FOOT_BOTTOM_HEIGHT, __MAIN_WIDTH, FOOT_BOTTOM_HEIGHT) bgColor:COLOR_HEXSTRING(@"#FFFFFF") onView:self.view];
    [Factory viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, 0.5) bgColor:[Theme lineNewColor] onView:footBottomView];
    
    CGFloat titleLabelX = 22 * __MAIN_RATIO_375;
    CGFloat titleLabelW = 40;
    CGFloat titleLabelH = 21;
    
    CGFloat detailTextLabelH = 20;
    
    CGFloat submitButtonW = 130 * __MAIN_RATIO_375;
    CGFloat submitButtonX = __MAIN_WIDTH - submitButtonW;
    
    CGFloat titleLabelY = (FOOT_BOTTOM_HEIGHT - titleLabelH - detailTextLabelH - 2) / 2;
    CGFloat detailTextLabelW = __MAIN_WIDTH - submitButtonW - titleLabelX;
    CGFloat detailTextLabelY = FOOT_BOTTOM_HEIGHT - titleLabelY - detailTextLabelH;
    
    UILabel * countTextlabel =[Factory labelWithFrame:CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH) font:FONT_DEFAULT_Light(16) text:@"合计:" textColor:[Theme wordColor] onView:footBottomView textAlignment:NSTextAlignmentLeft];
    countTextlabel.backgroundColor = [UIColor clearColor];
    
    //金额数目
    self.moneyCountLabel = [Factory labelWithFrame:CGRectMake(countTextlabel.frame.origin.x + countTextlabel.frame.size.width, countTextlabel.frame.origin.y, __MAIN_WIDTH - submitButtonW - (countTextlabel.frame.origin.x + countTextlabel.frame.size.width), countTextlabel.frame.size.height) font:FONT_DEFAULT_Light(16) text:[NSString stringWithFormat:@"0元"] textColor:[Theme orangeColor] onView:footBottomView textAlignment:NSTextAlignmentLeft];
    self.moneyCountLabel.backgroundColor = [UIColor clearColor];
    //打开挣点抵扣

    
    [Factory labelWithFrame:CGRectMake(titleLabelX, detailTextLabelY, detailTextLabelW, detailTextLabelH) font:FONT_DEFAULT_Light(12) text:@"支付宝在线支付" textColor:COLOR_HEXSTRING(@"#acacac") onView:footBottomView textAlignment:NSTextAlignmentLeft];
    
    __weak __typeof(self) wself = self;
    self.submitButton = [Factory buttonWithFrame:CGRectMake(submitButtonX, 0, submitButtonW, FOOT_BOTTOM_HEIGHT) bgColor:[Theme orangeColor] title:@"提交订单" textColor:[UIColor whiteColor] click:^{
        
        NSString * earnMoneyStr;
        NSString * totalMoneyStr;
        if (wself.isSwitchOn) {
            CGFloat moneyFloat = (CGFloat)(wself.earnMoneyInt / 100.0);
            CGFloat moneyCountFloat = (CGFloat)((((NSInteger)(wself.totalPriceFloat * 100)) - wself.earnMoneyInt) / 100.0);
            earnMoneyStr = [NSString stringWithFormat:@"-%.02f元",moneyFloat];

            totalMoneyStr = [NSString stringWithFormat:@"%.02f元", moneyCountFloat];

        }
        else
        {
            earnMoneyStr = [NSString stringWithFormat:@"-0元"];
            totalMoneyStr = [NSString stringWithFormat:@"%.02f元",wself.totalPriceFloat];
        }
        
        //打开挣点抵扣
        if (wself.isSwitchOn) {
            [MaintenanceMgr sharedInstance].orderModel.pointNum = wself.earnMoneyInt;
        }else
        {
            [MaintenanceMgr sharedInstance].orderModel.pointNum = 0;
        }
        
        [UmengMgr event:ICZ_Maintenance_Order_Create];
        [wself.navigationController pushViewController:[[[OrderSureViewController alloc] init] setupNavBack] animated:YES];
    } onView:footBottomView];
    [self.submitButton setEnabled:([[[self.moneyCountLabel.text componentsSeparatedByString:@"元"] firstObject] integerValue] > 0 ? YES : NO)];
    [self.submitButton setBackgroundColor:(self.submitButton.enabled ? [Theme orangeColor] : [Theme wordGrayColor])];
    self.submitButton.titleLabel.textAlignment = NSTextAlignmentCenter;
}
- (void)loadFootViewData
{
    self.earnMoneyInt = [self loadEarnMoneyInt:self.refreshMgr.refreshMoney.currentMoney withPrice:self.totalPriceFloat];
    if (self.isSwitchOn) {
        self.moneyCountLabel.text = [NSString stringWithFormat:@"%.02f元", (CGFloat)((((NSInteger)(self.totalPriceFloat * 100)) - self.earnMoneyInt) / 100.0)];
    }else
    {
        self.moneyCountLabel.text = [NSString stringWithFormat:@"%.02f元", [MaintenanceMgr sharedInstance].producePrice];
    }
}
- (NSArray *)sectionTitleArray
{
    return @[@"我的车辆",MAINTENANCEMGR.choiceServiceList.title,@"挣点抵扣"];
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, __MAIN_HEIGHT_64_TABBAR - FOOT_BOTTOM_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.backgroundColor = [Theme backGroundColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView .showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
}
#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionTitleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section == 0 ? 1 : (section == 1 ? (self.dataArray.count + 1) : 1));
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return (section == 0 ? 0 : (section == 1 ? SECTION_HEIGHT : SECTION_HEIGHT_SMALL));
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 0 ? CELL_HEIGHT_NORMALL : (indexPath.section == 1 ? [ChangeMTCell getCellHeight] : (CELL_HEIGHT_CONTENT + SECTION_HEIGHT_SMALL)));
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return  0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * backHeadView = [Factory viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, SECTION_HEIGHT) bgColor:[Theme backGroundColor] onView:nil];
    if(section == 1)[Factory labelWithFrame:CGRectMake(22 * __MAIN_RATIO_375, 0, backHeadView.frame.size.width, backHeadView.frame.size.height) font:FONT_DEFAULT_Light(15) text:self.sectionTitleArray[section] textColor:[Theme wordColor] onView:backHeadView textAlignment:NSTextAlignmentLeft];
    
    return backHeadView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell;
    if (indexPath.section == 0) {
        static NSString * cellID = @"carCellID";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            CGFloat leftLabelX = 22 * __MAIN_RATIO_375;
            UILabel * leftLabel = [Factory labelWithFrame:CGRectMake(leftLabelX, 0, __MAIN_WIDTH - leftLabelX * 2, CELL_HEIGHT_NORMALL) font:FONT_DEFAULT_Light(14) text:@"" textColor:[Theme wordColor] onView:cell textAlignment:NSTextAlignmentLeft];
            leftLabel.tag = 14;
        }
        
        UILabel * leftLabel = (UILabel *)[cell viewWithTag:14];
        leftLabel.text = [MaintenanceMgr sharedInstance].infoModel.bopaiCarTypeName;
        
    }else if(indexPath.section == 1)
    {
        static NSString * cellID = @"changeCellID";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[ChangeMTCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            
        }
        NSString * imageNameStr = (indexPath.row < self.dataArray.count ? self.iconImageDic[((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName] : @"servicePriceMTImage");
//        ((ChangeMTCell *)cell).iconImageStr = ([imageNameStr isNotNil] ? imageNameStr : @"newProjectNormallImage");
        [((ChangeMTCell *)cell).lineView setHidden:(indexPath.row == 0 ? YES : NO)];
        [((ChangeMTCell *)cell).rightImageV setHidden:(indexPath.row == self.dataArray.count ? YES : NO)];
        if(indexPath.row == self.dataArray.count)[((ChangeMTCell *)cell).moneyTitleLabel setFrameOriginX:__MAIN_WIDTH - 17 - ((ChangeMTCell *)cell).moneyTitleLabel.frame.size.width];
        
        if ([[MaintenanceMgr sharedInstance].choiceProduce count] > 0) {
            MaintenanceServiceCategoriesSelectionModel * model = (indexPath.row < self.dataArray.count ? [[MaintenanceMgr sharedInstance].choiceProduce objectForKey:((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName] : nil);
            ((ChangeMTCell *)cell).nameTitleStr = (indexPath.row < self.dataArray.count ? [NSString stringWithFormat:@"%@%@",model.accessoryName,((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName] : @"服务费");
            ((ChangeMTCell *)cell).moneyStr = (indexPath.row < self.dataArray.count ? [NSString stringWithFormat:@"%.0f元",model.totalPrice] : [NSString stringWithFormat:@"%.0f元",[MaintenanceMgr sharedInstance].choiceServiceList.model.servicePrice]);
            
        }else
        {
            ((ChangeMTCell *)cell).nameTitleStr = [NSString stringWithFormat:@"未选择  %@",(indexPath.row < self.dataArray.count ? ((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName : [NSString stringWithFormat:@"%.0f元",[MaintenanceMgr sharedInstance].choiceServiceList.model.servicePrice])];
            
        }
    }else
    {
        static NSString * cellID = @"payCellID";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            
            CGFloat leftLabelX = 22 * __MAIN_RATIO_375;
            
            CGFloat switchW = 48;
            CGFloat switchH = 31;
            
            CGFloat leftLabelW = __MAIN_WIDTH - leftLabelX * 2 - switchW;
            UILabel * leftLabel = [Factory labelWithFrame:CGRectMake(leftLabelX, 0, leftLabelW, CELL_HEIGHT_CONTENT) font:FONT_DEFAULT_Light(14) text:@"" textColor:[Theme wordColor] onView:cell textAlignment:NSTextAlignmentLeft];
            leftLabel.tag = 31;
            
            UISwitch * swichClick = [[UISwitch alloc]initWithFrame:CGRectMake(__MAIN_WIDTH - switchW - leftLabelX, (CELL_HEIGHT_CONTENT - switchH) / 2, switchW, switchH)];
            swichClick.onTintColor = [Theme mainColor];
            [cell addSubview:swichClick];
            swichClick.tag = 37;
            [Factory viewWithFrame:CGRectMake(0, CELL_HEIGHT_CONTENT, __MAIN_WIDTH, SECTION_HEIGHT_SMALL) bgColor:[Theme backGroundColor] onView:cell];
        }
        UILabel * leftLabel = (UILabel *)[cell viewWithTag:31];
        UISwitch * swichClickView = (UISwitch *)[cell viewWithTag:37];
        swichClickView.on = self.isSwitchOn;
        [swichClickView addTarget:self action:@selector(swithcClick:) forControlEvents:UIControlEventTouchUpInside];
        
        self.earnMoneyInt = [self loadEarnMoneyInt:self.refreshMgr.refreshMoney.currentMoney withPrice:self.totalPriceFloat];
        NSInteger earnMoneyInt = self.earnMoneyInt;
        NSString * earnMoneyStr = [NSString stringWithFormat:@"可使用%zd挣点抵扣 ",earnMoneyInt];
        CGFloat moneyFloat = (CGFloat)(earnMoneyInt / 100.0);
        NSString * useMoneyStr = [NSString stringWithFormat:@"%@%.02f元",earnMoneyStr,moneyFloat];
        
        NSMutableAttributedString * moneyAttributeStr = [[NSMutableAttributedString alloc]initWithString:useMoneyStr];
        NSRange moneyTextRange = NSMakeRange([earnMoneyStr length], ([useMoneyStr length] - [earnMoneyStr length]));
        [moneyAttributeStr addAttribute:NSForegroundColorAttributeName value:[Theme orangeColor] range:moneyTextRange];
        //如果是0 当前无可使用挣点
        
        leftLabel.attributedText = (earnMoneyInt == 0 ? [[NSMutableAttributedString alloc] initWithString:@"当前无可使用挣点"] : moneyAttributeStr) ;
        [swichClickView setEnabled:(earnMoneyInt == 0 ? NO : YES)];
        //打开挣点抵扣
        if (self.isSwitchOn) {
            self.moneyCountLabel.text = [NSString stringWithFormat:@"%.02f元", (CGFloat)((((NSInteger)(self.totalPriceFloat * 100)) - self.earnMoneyInt) / 100.0)];
        }else
        {
            self.moneyCountLabel.text = [NSString stringWithFormat:@"%.02f元", [MaintenanceMgr sharedInstance].producePrice];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)swithcClick:(UISwitch *)switchSender
{
    self.isSwitchOn = [switchSender isOn];
    
    [self.tableView reloadData];
    [self loadFootViewData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //保养服务
    if (indexPath.section == 1 && indexPath.row < self.dataArray.count) {
        
        [UmengMgr event:ICZ_Maintenance_Product];
        
//        NSString * imageNameStr = self.iconImageDic[((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName];
        ChangeDetailMTController * vc = [[ChangeDetailMTController alloc] initWithDataArray:((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).selectionModels withAddNameStr:((MaintenanceServiceCategoriesModel *)self.dataArray[indexPath.row]).categoryName ];
        ChangeMTCell * changeMTCell = (ChangeMTCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        __weak __typeof(self) wself = self;
        vc.selectChangeDetailModel = ^(MaintenanceServiceCategoriesSelectionModel * model)
        {
            NSString * choiceKeyStr = ((MaintenanceServiceCategoriesModel *)wself.dataArray[indexPath.row]).categoryName;
            [[MaintenanceMgr sharedInstance].choiceProduce setObject:model forKey:choiceKeyStr];
            changeMTCell.nameTitleStr = [NSString stringWithFormat:@"%@%@",model.accessoryName,((MaintenanceServiceCategoriesModel *)wself.dataArray[indexPath.row]).categoryName];
            changeMTCell.moneyStr = [NSString stringWithFormat:@"%.0f元", model.totalPrice];
        };
        
        [self.navigationController pushViewController:[vc setupNavBack] animated:YES];
        
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    __weak __typeof(self) wself = self;
    [[MaintenanceMgr sharedInstance] totalPrice:^(CGFloat price) {
        wself.totalPriceFloat = price;
        
    }];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.submitButton) {
        [self.submitButton setEnabled:([MaintenanceMgr sharedInstance].allChoiced ? YES : NO)];
        [self.submitButton setBackgroundColor:(self.submitButton.enabled ? [Theme orangeColor] : [Theme wordGrayColor])];
    }
    
    [self.refreshMgr.refreshMoney startRefreshWithTimeInterval:0];
    
    [self.tableView reloadData];
    [self loadFootViewData];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.refreshMgr.refreshMoney stopRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
